﻿using Bouyei.GeoCore.Converters;
using Bouyei.GeoCore.Geometries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bouyei.GeoCore.GeoParsers.SpatiaLite
{
    public class GeometryReader : BaseBytes
    {
        private Wkb.GeometryReader wkbReader = null;
        private int srid = 0;

        public Coordinate Min { get; set; }

        public Coordinate Max { get; set; }

        public GeometryReader(byte[] buffer, int offset = 0)
              : base(buffer, buffer[1] == 1 ? ByteOrder.LittleEndian : ByteOrder.BigEndian, offset)
        {
            wkbReader = new Wkb.GeometryReader(buffer, offset + 39, ByteOrder);
        }

        public Geometry Reader()
        {
            if ((Buffer.Length - Offset) < 45)
                throw new Exception("invalid blob geometry");

            if (Buffer[Offset] != (byte)BlobMark.MARK_START)
                throw new Exception("invalid start signature");

            if (Buffer[Buffer.Length - 1] != (byte)BlobMark.MARK_END)
                throw new Exception("invalid end signature");

            if (Buffer[Offset + 38] != (byte)BlobMark.MARK_MBR)
                throw new Exception("invalid MBR signature");

            Min = new Coordinate(bitExt.ToDouble(Buffer, Offset + 6),
                bitExt.ToDouble(Buffer, Offset + 14));
            Max = new Coordinate(bitExt.ToDouble(Buffer, Offset + 22),
                bitExt.ToDouble(Buffer, Offset + 30));

            srid = bitExt.ToInt32(Buffer, Offset + 2);
            var geo = wkbReader.Reader();
            geo.SRID = srid;

            return geo;
        }
    }
}
